package org.aplombh.java.study.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class Solution {

    private static CountDownLatch latch = new CountDownLatch(2);

    // List<Double> = [0.1,0.2,0.3,0.4,0.5,0.6,0.7]
    public static double solution(List<Double> num) {
        CountMeanThread countMeanThread =  new CountMeanThread(num,latch);
        countMeanThread.start();
        CountMidThread countMidThread =  new CountMidThread(num,latch);
        countMidThread.start();
        // 等待门栓countdown到0,放行
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Math.max(countMeanThread.mean,countMidThread.mid);
    }
}

class CountMeanThread extends Thread {

    List<Double> num;

    double sum = 0.0;

    double mean = 0.0;

    CountDownLatch latch;

    public CountMeanThread(List<Double> num,CountDownLatch latch){
        this.num = num;
        this.latch = latch;
    }

    @Override
    public void run(){
        for(int i = 0;i < num.size();i++){
            sum = sum + num.get(i);
        }
        mean = sum / num.size();
        latch.countDown();
        System.out.println("mean: " + mean);
    }
}

class CountMidThread extends Thread {

    List<Double> num;

    double sum = 0.0;

    double mid = 0.0;

    CountDownLatch latch;

    public CountMidThread(List<Double> num,CountDownLatch latch){
        this.num = num;
        this.latch = latch;
    }

    @Override
    public void run(){
        for(int i = 0;i < num.size();i++){
            sum = sum + num.get(i);
        }
        // 对list排序,中位数就是num[num.length/2];
        Arrays.sort(new List[]{num});
        mid = num.get(num.size() / 2);
        System.out.println("mid: " + mid);
        latch.countDown();
    }
}

class ShowMeBug {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        List<Double> num =  new ArrayList(10);
        num.add(0.1);
        num.add(0.2);
        num.add(0.3);
        num.add(0.7);
        num.add(0.9);
        System.out.println("Hello World!");
        double maxNum = Solution.solution(num);
        System.out.println("maxNum: " + maxNum);
    }
}

